﻿/*文件注释
 * ===============================================================================
 * 说明：
 * 作者：曾永佑
 * 版本：V1.0
 * 创建日期：2013-02-28
 * 完成日期： 
 * 修改纪录：  
 * ===============================================================================
 */  
        
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web; 
using System.Web.Mvc;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System; 

namespace SRF.UI.Html
{
    public static class UserExtensions
    {
        static SRF.Data.DBHelperBase dbhelper = Data.DBHelperFactory.GetDBHelper();

        /// <summary>
        /// 用户名
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static MvcHtmlString UserName(this HtmlHelper htmlHelper, string userId)
        {
            return new MvcHtmlString(GetUserName(userId));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <typeparam name="TProperty"></typeparam>
        /// <param name="htmlHelper"></param>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static MvcHtmlString UserNameFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            var userId = "";
            if (metadata.Model != null)
                userId = metadata.Model.ToString();

            return new MvcHtmlString(GetUserName(userId));
        }

        private static string GetUserName(string userId)
        {
            if (string.IsNullOrEmpty(userId))
                return "";
            else
            {
                return dbhelper.GetQuery("select name from sec_user where id=:id")
                       .SetParameter("id", userId).UniqueResult().ToString();
            }
        }
    }
}